package com.qidian.tcba.auth.service.impl;

import com.qidian.tcba.auth.dao.AuthUserMapper;
import com.qidian.tcba.auth.dto.UserDTO;
import com.qidian.tcba.auth.entity.UserEntity;


import com.qidian.tcba.auth.param.LoginParam;
import com.qidian.tcba.auth.service.AuthUserService;
import com.qidian.tcba.auth.service.impl.security.token.JwtManager;
import com.qidian.tcba.auth.utils.UserDetail;
import com.qidian.tcba.utils.BeanMapper;
import com.qidian.tcba.utils.BusinessException;
import com.qidian.tcba.utils.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author:fyl
 * @date 2021/7/22 20:54
 * @Modified By:
 * @Modified Date:
 * @Description:
 */
@Service
public class AuthUserServiceImpl implements AuthUserService, UserDetailsService {
    @Autowired
    private AuthUserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtManager jwtManager;

    @Override
    public int save(UserEntity user) {
        user.setOrgId(1);
        return userMapper.insert(user);
    }

    @Override
    public UserDTO login(LoginParam param) {
        // 根据用户名查询出用户实体对象
        UserEntity user = userMapper.selectByUsername(param.getUsername());
        // 若没有查到用户或者密码校验失败则抛出异常
        if (user == null || !passwordEncoder.matches(param.getPassword(), user.getPassword())) {
            throw new BusinessException(new Message("账号密码错误"));
        }
        UserDTO userDTO = BeanMapper.map(user, UserDTO.class);
                // 生成token
        userDTO.setToken(jwtManager.generate(user.getUsername()));
        return userDTO;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询出用户实体对象
        UserEntity user = userMapper.selectByUsername(username);
        // 若没查询到一定要抛出该异常，这样才能被Spring Security的错误处理器处理
        if (user == null) {
            throw new UsernameNotFoundException("没有找到该用户");
        }
        // 走到这代表查询到了实体对象，那就返回我们自定义的UserDetail对象（这里权限暂时放个空集合，后面我会讲解）
        return  new UserDetail(user, null);
    }
}

